#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/9/1 14:51
# @Author : 闫峰
# @File    : set_amazon_sales_ban.py

import os
import re
import time
from common.setting import ensure_path_sep
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database
from utils.mysqlUtils.sql_server_utils import MSSQL

current_path = os.path.abspath(__file__)
current_dir = os.path.dirname(current_path)
path_list = current_path.split("\\")
dis_path = "\\".join(path_list[-2:-1])


def remove_file(info_path):
    if os.path.exists(info_path):
        os.remove(info_path)
    else:
        print(f"{info_path} 不存在")


info_path = ensure_path_sep(f"\\logs\\info-{dis_path}{time.time()}")
error_path = ensure_path_sep(f"\\logs\\\error-{dis_path}{time.time()}.log")
warning_path = ensure_path_sep(f"\\logs\\warning-{dis_path}{time.time()}.log")
remove_file(info_path)
remove_file(error_path)
remove_file(warning_path)
INFO = LogHandler(info_path, level='info')
ERROR = LogHandler(error_path, level='error')
WARNING = LogHandler(warning_path, level='warning')


class Set_amazon_sales_ban:
    db = MSSQL(ensure_path_sep("\\config\\config.yaml"), "sqlserver_db_erp_base")
    insert_db = Database(ensure_path_sep("\\config\\ceshi_mysql_config.yaml"), "log_db")

    def set_amazon_sales_ban(self):
        sql = """
        SELECT top 10000 id,sku,OperationTxt FROM [dbo].[RB_Product_Log] WHERE id > %s ORDER BY id
        """
        # offset = 160073124
        # batch_size = 1000
        offset = 864319240
        count = 0
        while True:
            # 获取一批数据

            res = self.db.ExecQuery(sql, (offset,))
            # 如果没有数据了，退出循环
            if not res:
                break

            # 处理数据
            for row in res:
                # id, sku ,OperationTxt = row
                is_exist = self.re_str(row)
                offset = row[0]
                if is_exist:
                    # 插入数据库
                    insert_sql = """
                    INSERT IGNORE INTO set_amazon_sales_ban (erp_id, sku, text) 
                    VALUES (%s, %s, %s);
                    """
                    row1 = self.insert_db.execute(insert_sql, (row[0], row[1], row[2]))
                    if row1 == 0:
                        ERROR.logger.error(f"""
                    INSERT IGNORE INTO set_amazon_sales_ban (erp_id, sku, text) 
                    VALUES ({row[0]}, {row[1]}, {row[2]});
                    插入失败
                        """)

                # print(f'id: {id}, sku: {sku}, OperationTxt: {OperationTxt}')

            # 更新分页参数
            count += 10000
            INFO.logger.info(f"已经执行完{count}数据")
            # offset += 100000

    def re_str(self, row):
        pattern = r"服务自动设置亚马逊禁售国家：沙特阿拉伯,阿拉伯联合酋长国"
        match = re.search(pattern, row[2])
        if match:
            # print("匹配成功！")
            return True
        else:
            # print("未找到匹配的文本。")
            return False


if __name__ == '__main__':
    Set_amazon_sales_ban().set_amazon_sales_ban()
